<?php

namespace app\material\controller\api;

use app\ApiController;
use app\mainadmin\model\ArticleModel;
use app\mainadmin\model\SettingsModel;
use app\material\model\MaterialCategoryModel;
use app\material\model\MaterialListModel;
use app\material\model\MaterialOrderModel;
use app\member\model\AccountModel;
use think\Db;
use think\Exception;

class Index extends ApiController
{
    public function initialize()
    {
        parent::initialize();
        $this->Model = new MaterialListModel();
    }

    public function category()
    {
        $cateModel = new MaterialCategoryModel();
        $list = $cateModel->getList(['is_show' => 1]);
        $this->success('success','',$list);
    }

    public function index()
    {
        $uid = $this->userInfo['user_id'];
        $page = input('page', 1, 'intval');
        $limit = input('limit', 10, 'intval');
        $cid = input('cid', '');
        $btype = input('btype', '');
        $where[] = ['is_audit','=',1];
        $where[] = ['status','=',1];
        $where[] = ['is_del','=',0];
        if($cid){
            $where[] = ['cid','=',$cid];
        }
        if($btype){
            switch ($btype){
                case 'collect':
                    $ids =  Db::name('material_collect')->where(['uid' => $this->userInfo['user_id']])->column('mid');
                    $where[] = ['id','in',$ids];
                    break;
                case 'video':
                    $where[] = ['type','in',3];
                    break;
                case 'yingxiao':
                    $where[] = ['type','in',1];
                    break;
            }
        }
        $list = $this->Model->getList($where,$uid,$page,$limit);
        $this->success('success','',$list);
    }

    public function self()
    {
        $uid = $this->userInfo['user_id'];
        $page = input('page', 1, 'intval');
        $limit = input('limit', 10, 'intval');
        $is_audit = input('is_audit', '');
        $where[] = ['uid','=',$uid];
        $where[] = ['status','=',1];
        $where[] = ['is_del','=',0];
        if($is_audit !== ''){
            $where[] = ['is_audit','=',$is_audit];
        }

        $list = $this->Model->getList($where,$uid,$page,$limit);
        $this->success('success','',$list);
    }

    public function collect()
    {
        $mid = input('mid', 0, 'intval');
        if(!$mid){
            $this->error('参数错误');
        }
        $count = Db::name('material_collect')->where(['uid' => $this->userInfo['user_id'],'mid' => $mid])->count();
        if($count){
            Db::name('material_collect')->where(['uid' => $this->userInfo['user_id'],'mid' => $mid])->delete();
            $this->success('取消成功');
        }else{
            Db::name('material_collect')->insert(['uid' => $this->userInfo['user_id'],'mid' => $mid,'add_time' => time()]);
            $this->success('收藏成功');
        }
    }

    public function info()
    {
        $id = input('id', 0, 'intval');
        $data = $this->Model->getOne($id,$this->userInfo['user_id']);
        if(!$data['share_img']){
            $org_path = $data['cover'];
            $path_arr = explode('/',$org_path);
            $path_arr[count($path_arr) - 1] = 'share_'.$path_arr[count($path_arr)-1];
            $new_path = implode('/',$path_arr);
            $image = \think\Image::open($_SERVER['DOCUMENT_ROOT'].$org_path);
            if($image){
                $res = $image->thumb(150,150,\think\Image::THUMB_CENTER)->save($_SERVER['DOCUMENT_ROOT'].$new_path);
                if($res){
                    $resp = $image->water($_SERVER['DOCUMENT_ROOT'].'/static/images/play.png',\think\Image::WATER_CENTER)->save($_SERVER['DOCUMENT_ROOT'].$new_path);
                    if($resp){
                        $this->Model->where(['id' => $id])->update(['share_img' => $new_path]);
                    }
                }
            }
        }
        $this->success('success','',$data);
    }

    public function save()
    {
        $post = input('post.');
        $id = $post['id'];
        if($post['type'] != 1 && empty($post['cover'])){
            $post['cover'] = getVideoCover($post['video']);
        }
        if($id){
            $data = [
                'cid' => $post['cid'],
                'type' => $post['type'],
                'content' => $post['content'],
                'images' => $post['images'],
                'cover' => $post['cover'],
                'video' => $post['video'],
                'is_audit' => 0,
            ];
            $r = $this->Model->where('id',$id)->update($data);
        }else{
            $data = [
                'uid' => $this->userInfo['user_id'],
                'cid' => $post['cid'],
                'type' => $post['type'],
                'content' => $post['content'],
                'images' => $post['images'],
                'cover' => $post['cover'],
                'video' => $post['video'],
                'status' => 1,
                'is_audit' => 0,
                'goods_id' => $post['goods_id'],
                'add_time' => time()
            ];
            $r = $this->Model->insert($data);
        }

        if($r !== false)
            $this->success('发布成功，等待审核');
        else
            $this->error('发布失败');
    }

    public function config()
    {
        $setModel = new SettingsModel();
        $material_banner = $setModel->where(['name' => 'material_banner'])->value('data');
        $material_auth = $setModel->where(['name' => 'material_auth'])->value('data');
        $data = [
            'material_banner' => $material_banner,
            'material_auth' => $material_auth ? explode(',',$material_auth) : []
        ];
        $this->success('success','',$data);
    }

    public function delete()
    {
        $map['id'] = input('id', 0, 'intval');
        if ($map['id'] < 1) return $this->error('传递参数失败！');
        $map['uid'] = $this->userInfo['user_id'];
        $row = $this->Model->where($map)->find();
        if(!$row){
            return $this->error('不是您的素材！');
        }
        $res = $this->Model->where($map)->update(['is_del' => 1]);
        if ($res < 1) return $this->error();
        return $this->success('删除成功.');
    }

    public function pay()
    {
        $id = input('id', 0, 'intval');
        if ($id < 1) return $this->error('传递参数失败！');
        $info = $this->Model->where('id',$id)->find();
        if(!$info){
            return $this->error('素材不存在');
        }
        if($this->userInfo['account']['integral_money'] < $info['price']){
            return $this->error('您的积分不足');
        }
        $model = new MaterialOrderModel();
        $data = [
            'uid' => $this->userInfo['user_id'],
            'mid' => $id,
            'paid' => 0,
            'price' => $info['price'],
            'add_time' => time()
        ];
        $order_id = $model->insertGetId($data);
        //减积分
        $md5Log = strtolower(md5($order_id . '_' . $this->userInfo['user_id'] . '_解锁素材_' . $id));
        $AccountModel = new AccountModel();
        $changedata['change_desc'] = '解锁素材';
        $changedata['change_type'] = 48;
        $changedata['by_id'] = $order_id;
        $changedata['from_uid'] = 0;
        $changedata['integral_money'] = -$info['price'];
        $changedata['bean_value'] = 0;
        $changedata['total_dividend'] = 0;
        $changedata['md5log'] = $md5Log;
        $res = $AccountModel->change($changedata, $this->userInfo['user_id'], false);
        if($res){
            $model->where('id',$order_id)->update(['paid' => 1]);
            //加积分
            if($info['uid']){
                $md5Log = strtolower(md5($order_id . '_' . $info['uid'] . '_销售素材_' . $id));
                $AccountModel = new AccountModel();
                $changedata['change_desc'] = '销售素材';
                $changedata['change_type'] = 49;
                $changedata['by_id'] = $order_id;
                $changedata['from_uid'] = $this->userInfo['user_id'];
                $changedata['integral_money'] = $info['price'];
                $changedata['bean_value'] = 0;
                $changedata['total_dividend'] = 0;
                $changedata['md5log'] = $md5Log;
                $AccountModel->change($changedata, $info['uid'], false);
            }
            return $this->success('支付成功');
        }else{
            return $this->error('支付失败');
        }
    }
}
